<template>
	<view class="main animated fadeIn faster">
		<view class="content position-fixed z-index-99" :style="{'paddingTop':$store.state.statusBarHeight+'px','top':'0'}">
			<view class="title">
				<view class="pl-2 mr-4" @click="goBack"><text class="iconfont icon-31fanhui1 font30 mr-5"></text></view>
				<text class="" :style="{marginRight: IsShow? '0' : '90rpx'}">{{title}}</text>
				<view style="width: 90rpx;"></view>
				<!-- <view v-if="IsShow" @click="GotoBillPage" class="" style="width: 90rpx;">账单</view> -->
			</view>
		</view>
		<view class="mt-200 px-2">
			<view class="d-flex d-flex-between">
				<view class="d-flex d-flex-middle pl-1">
					<text class="font-bold font30">嗒币余额：</text>
					<view class="font-bold font40">{{$store.state.user.availableAmount}}</view>
				</view>
				<view @click="GotoBillPage" v-if="!IsShow" class="mr-1">账单</view>
			</view>
			<view class="mt-3 rounded20 px-1" style="background: #f5f5f5;">
				<view class="font-bold font30 pt-2">请选择充值嗒币数量</view>
				<view class="font24 mt-2" style="color: #595757;">嗒币充值比例为{{device?'1:10':'1:7'}},充值完成后不可体现哦</view>
				<view class="d-flex d-flex-between d-flex-wrap mt-3 pb-2" style="width: 100%;">
					<view :class="['d-flex-column','rounded20','mt-2','py-2',current == i.id? 'borderL' : '']" style="border: 1px solid #858585; width: 28%;" v-for="(i,index) in rechargeList" :key="index" @click="changeCurrent(i.id)">
						<view class="d-flex d-flex-center d-flex-middle">
							<image src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/app/%E7%BB%84%20554.png" mode="widthFix" style="width: 35rpx; height: 35rpx;"></image>
							<view :class="['font-bold','font36', current == i.id? 'current' : '']" style="margin-left: 4rpx;">{{i.coinCount}}</view>
						</view>
						<view :class="['text-center', current == i.id? 'current' : '']" style="color: #504e4e;">￥{{device?i.androidPrice:i.iosPrice}}</view>
					</view>
				</view>
			</view>
			<view class="d-flex d-flex-middle d-flex-center mt-2 mb-4">
				<checkbox class="d-flex-btn" :checked="isChecked" style="transform:scale(0.6);margin-top: 4rpx;" @click="isChecked = !isChecked"></checkbox>
				<!-- <checkbox value="r1" :checked="isChecked" style="transform:scale(0.6); margin-top: 4rpx;"/>阅读并同意</checkbox> -->
				<text class="font24 color999" @click="isChecked = !isChecked">我已阅读并同意</text>
				<text style="color: #50a2c7;" @click="toCoinPolicy">《小嗒组队嗒币充值服务协议》</text>
				
				
			</view>
			<view class="linerbg colorfff text-center py-2 rounded40" style="width: 80%; margin: 0 auto 50rpx;" @click="pay()">支付</view>
			<view class="rounded20 pl-3 pb-2" style="background: #f6f6f6; overflow: hidden;">
				<view class="mt-4" style="color: #585858;">充值说明:</view>
				<view style="color: #585858; margin-top: 15rpx;">1.用户在使用小嗒组队提供的充值服务前，应仔细阅读《小嗒组队嗒币充值服务协议》，如用户不同意本服务协议，请停止使用小嗒组队提供的充值服务。</view>
				<view style="color: #585858; margin-top: 15rpx;">2.充值购买需要缓冲时间，请耐心等待。</view>
				<view style="color: #585858; margin-top: 15rpx;">3.请根据个人需求，理性消费。</view>
				<view style="color: #585858; margin-top: 15rpx;">4.未成年人禁止充值消费。</view>
				<view style="color: #585858; margin-top: 15rpx;">5.若充值异常，请咨询小嗒组队客服。</view>
			</view>
			<!-- <view class="d-flex d-flex-end">
				<view class="GrabOrdersBtn">
					<view class="head_portrait">
						<image src="../../static/images/logo.png"></image>
						<view class="b_img">
							<image src="../../static/images/logo.png"></image>
						</view>
					</view>
					<view class="txt">7位大神抢单了</view>
					<view class="arr_icon">
						<image src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/app/%E7%BB%84%202457.png" mode=""></image>
					</view>
				</view>
			</view> -->
		</view>
		 <uni-popup ref="couponPopup" type="bottom" background-color="#fff" border-radius="10px 10px 0 0">
		      <view class="coupon-list">
				  <view class="font32 text-center mt-1 mb-3">您有以下的优惠券可以使用</view>
		        <view v-for="(i, index) in couponList" :key="index" class="d-flex" style="height: 120rpx; width: 90%; margin: 0 auto 20rpx;">
		          <view class="Cover rounded10" style="width: 90rpx; height: 100%;">
		            <view class="d-flex d-flex-bottom d-flex-center colorfff" style="margin-top: 15rpx;">
		              <view style="margin-bottom: 5rpx;">￥</view>
		              <view class="font-bold" style="font-size: 40rpx;">{{ i.amount }}</view>
		            </view>
		            <view class="font16 mt-1 colorfff text-center">满{{ i.limitUseAmount == 0 ? i.amount : i.limitUseAmount }}元可用</view>
		          </view>
		          <view class="Coupon_item d-flex-middle d-flex bg-fff rounded10" style="flex: 1; padding: 10rpx;">
		            <view class="d-flex d-flex-column ml-3" style="flex: 1;">
		              <view class="font24 mt-1">{{ i.name }} </view>
		              <view class="font24" style=" flex: 1;color: #b5b5b5;">有效期:{{ i.assetsExpireTime }}到期</view>
		            </view>
		            <view class="btn1 colorfff mr-3 px-2 rounded10 font20" @click="touse(i.assetsId)">选择</view>
		          </view>
		        </view>
				
				
				<view class="btn ml-2  colorfff" style="width: 75%; background-image: linear-gradient(-90deg, #f7880c 0%, #fe7039 40%, #fe536f 60%, #fe4594 90%, #f73ea0 100%);" @click="unuse">不使用优惠券</view>
				
		      </view>
		     
		    </uni-popup>
		<uni-popup ref="purchasePopup" @change="PopupStatusChange"  type="bottom" background-color="#fff" border-radius="10px 10px 0 0">
			<view class="PayOptions d-flex-between pt-2" v-for="(item, index) in PayList" :key="item.id" @click="ChangePayOpt(index)">
				<view class="d-flex d-flex-middle d-flex-between">
					<view class="icon">
						<image :src="item.icon"></image>
					</view>
					<view class="option mr-1" style="margin-bottom: 4rpx;">{{item.name}}</view>
					<view v-if="item.desc" class="font22 px-3 rounded10" style="color: #FF9645; background: #f9e7c9;">{{item.desc}}</view>
				</view>
				<radio-group class="radio-group" @change="ChangePayOpt(index)">
				  <radio value="true" :checked="item.checked" style="    transform: scale(.6);" class="radio-style"></radio>
				</radio-group>
			</view>
			<view class="btn ml-2 colorfff linerbg" style="width: 75%;" @click="confirm">支付</view>
		</uni-popup>
		
		<view class="position-fixed top-0 left-0 right-0 bottom-0" style="background: rgba(0, 0, 0, .5);" v-show="showTips">
			<view class="bg-fff rounded15 position-relative" style="top: 50%; left: 50%; transform: translate(-50%, -50%); width: 80%;">
				<view class="d-flex d-flex-column">
					<view class="text-center py-5 font34" style="color: #dd524d; display: inline-block;">提示</view>
					<view class="text-center pb-4" style="color: #6c6c6c; display: inline-block;">支付成功，嗒币将在1-5分钟到账！</view>
				</view>
				<view class="text-center font32 py-3" style="border-top: 1px solid #ededed;" @click="showTips = false">
					我知道了
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import { memberApi } from '../../http/memberApi';
	import store from '@/store/index.js';
	import { PayApi } from '../../http/PayApi';
	export default {
		data() {
			return {
				title: '充值',
				current: null,
				availableAmount:null,//可用余额
				isChecked: false,
				rechargeList: [
					{
					    "id": "1",
					    "name": "嗒币60个",
						"productId":"xdzd123",
					    "originalPrice": 6,
					    "price": 6,
					    "coinCount": 60,
					    "androidPrice": 6,
					    "iosPrice": 8.4
					},
					{
					    "id": "2",
					    "name": "嗒币180个",
						"productId":"xdzd180",
					    "originalPrice": 18,
					    "price": 18,
					    "coinCount": 180,
					    "androidPrice": 18,
					    "iosPrice": 25.2
					},
					{
					    "id": "3",
					    "name": "嗒币680个",
						"productId":"xdzd680",
					    "originalPrice": 68,
					    "price": 68,
					    "coinCount": 680,
					    "androidPrice": 68,
					    "iosPrice": 95.2
					},
					{
					    "id": "4",
					    "name": "嗒币980个",
						"productId":"xdzd980",
					    "originalPrice": 98,
					    "price": 98,
					    "coinCount": 980,
					    "androidPrice": 98,
					    "iosPrice": 137.2
					},
					{
					    "id": "5",
					    "name": "嗒币1680个",
						"productId":"xdzd168",
					    "originalPrice": 168,
					    "price": 168,
					    "coinCount": 1680,
					    "androidPrice": 168,
					    "iosPrice": 235.2
					},
					{
					    "id": "6",
					    "name": "嗒币1980个",
						"productId":"xdzd198",
					    "originalPrice": 198,
					    "price": 198,
					    "coinCount": 1980,
					    "androidPrice": 198,
					    "iosPrice": 277.2
					}
				],
				param:{},
				payParam:{},
				orderNo:'',
				device:true,//设备
				payWay:'',
				IsShow: null,
				showTips: false,
				 selectedCouponId: null  ,
				orderStr: null,
				 isRequesting: false,
				 WxpayParams:{},//微信支付参数
				 couponflag:false,
				 couponList:[],
				 iapChannel: null,
				 productList:[],
				PayList: [
					{
						id: 3,
						icon: 'https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/app/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20241115141319.png',
						name: '支付宝',
						desc: '推荐',
						value: 'Alipay',
						checked: true
					},
					{
						id: 2,
						icon: 'https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/app/Pay-Wechat.png',
						name: '微信',
						desc: '',
						value: 'Wechat',
						checked: false
					},
					
				]
			}
		},
		methods: {
			initIap(){
				plus.payment.getChannels((channels) => {
					for (let i = 0; i < channels.length; i++) {
						let channel = channels[i];
						if (channel.id === 'appleiap') {
							this.iapChannel = channel;
							break;
						}
					}
					this.requestIapOrder()
				}, (error) => {
					console.error('获取iap支付通道失败:', error.message);
				});
			},
			requestIapOrder() {
				if (this.iapChannel) {
					let ids = this.productList;
					this.iapChannel.requestOrder(ids, (res) => {
			          console.log('获取订单信息成功:', res);
			        }, (error) => {
			          console.error('获取订单信息失败:', error.code);
			        });
			      }
			},
			goBack() {
				uni.navigateBack({
					delta: 1
				});
			},
			ChangePayOpt(dex) {
				this.PayList[dex].checked = true
				this.PayList.forEach((i, index) => {
					if(dex !== index) {
						this.PayList[index].checked = false
					}
				})
			},
			unuse(){//不使用优惠券
				this.param.id=this.current;
				 		
				this.param.sourceType=this.device?'1':'2';
				this.$refs.couponPopup.close();
				this.createOrder(this.param);
				  this.OpenpurchasePopup();
			},
			changeCurrent(id) {
				this.current = id
				console.log(this.current);
			},
			async createOrder(param){//创建订单
			let res=await memberApi.buyCoin(param);
				this.orderNo=res.orderNo;
				  console.log(res.orderNo);
			},
			async createPay(param){//支付单
				let res=await PayApi.Pay(param);
				if(param.payMethod==3){//支付宝支付
				this.orderStr=res.params.orderStr;
					this.payByAlipay();
				}
				if(param.payMethod==2){
					this.WxpayParams={};
					this.WxpayParams=res.params;
					console.log("wx:",this.WxpayParams);
					this.payByWxpay();
				}
								
			},
			GotoBillPage() {
				uni.navigateTo({
					url: '/pagesApp/bill/bill'
				})
			},
			toCoinPolicy(){
				uni.navigateTo({
					url: '/pagesApp/RechargeServiceAgreement/RechargeServiceAgreement'
				})
			},
			payByWxpay() {
						  
						  //   const payParams = {
						  //       appId: 'wx8e6e04072a44bb3e', // 微信开放平台上的 appId
						  //       timeStamp: '1737014370', // 时间戳，单位秒
						  //       nonceStr: 'rBwlwRTSm6vwEj6CVrgnGcUQonQL7xg0', // 随机字符串，长度为 32 个字符以下
						  //       prepayid: 'wx16155933165269d727fad216ee68660000', // 统一下单接口返回的 prepay_id 参数值，提交格式如：prepay_id=***
						  //       signType: 'MD5', // 签名算法，暂支持 MD5
								// partnerid: '1628758027',
						  //       paySign: 'UZSDinINWUd1RMVxJWqn6A2MAIKAXDVroVbzt+S2GFXw8245o3OGWR/MjRR15eFEq+xyK4HNvvmWZPU4KqqtNddvEivKAbu7t0LESDEy7mgG3EbSbMqkGjRqpKNvJqrY88Er5E4rG0umumosJaArYPUz2HONaRMVIhflXPpwYMYm4XljGtU2YTMmUeKT4UPjoHiweRJSOz6q6rpZgdBJYeQkIuPQBPxLa70hJ6hLbyCLfkEis86Zy2fm1QU9XTyqWFIXMZ7VEzi7PTiXEkQoFml8tqIdd+0LcOnBhZp8nVlyP5YnNmXOtAglmwU7tLPfca+fjqJ8o2zXAEr6MalKZw==', // 签名，具体签名方法见后端生成签名部分
						  //   };
						    // console.log(payParams);
						    // 调用 uni.requestPayment 发起支付
						    uni.requestPayment({
						        "provider": "wxpay", // 微信支付
								"orderInfo": {
						        "appid": this.WxpayParams.appid,
						        "timestamp":this.WxpayParams.timestamp,
						        "noncestr": this.WxpayParams.noncestr,
								"package": "Sign=WXPay", 
								"partnerid": this.WxpayParams.partnerId,
						        "prepayid": this.WxpayParams.prepayId, 
						        "sign": this.WxpayParams.sign
								},
								
						        success: (res) => {
						            console.log('支付成功', res);
									 this.$refs.purchasePopup.close();
						            // 支付成功的处理逻辑
									this.showTips = true
						        },
			       fail: (err) => {
			                   console.log('支付失败，错误信息：', err);
			                   if (err.errCode === 'xxx') { 
			                       // 可以根据不同的 errCode 进行不同的处理，这里的 xxx 是具体的错误码，例如用户取消支付的错误码
			                       console.log('用户取消支付');
			                   } else if (err.errCode === 'yyy') { 
			                       // 另一种错误码 yyy 的处理
			                       console.log('签名错误，请联系客服');
			                   } else {
			                       console.log('其他支付错误，请重试或联系客服');
			                   }
			                   uni.showToast({
			                       title: '支付失败',
			                       icon: 'none',
			                       duration: 2000
			                   });
			               }
			    });
			},
			
			
			
			payByAlipay() {
			   
	const orderStr = this.orderStr;
    if (!orderStr) {
        console.error('订单字符串为空，无法进行支付');
        return;
    }

    // 调用 uni.requestPayment 方法
    uni.requestPayment({
        provider: 'alipay', // 指定支付提供商为支付宝
        orderInfo: orderStr, // 订单信息
        success: (res) => {
            console.log('支付成功:', res);
            this.$refs.purchasePopup.close();
			this.showTips = true
        },
        fail: (err) => {
            console.error('支付失败:', err);
           uni.showToast({
               title: '支付失败',
               icon: 'none', // 使用'none'图标，只显示文字
               duration: 1000 // 显示持续时间
             });
        }
    });
			},
			PopupStatusChange(e) {
				// 关闭弹窗将支付选项恢复默认
				if(!e.show) {
					setTimeout(() => {
						this.PayList.forEach((i, index) => {
							if(index === 0) {
								this.PayList[index].checked = true
							} else {
								this.PayList[index].checked = false
							}
						})
					},500)
				}
			},
			confirm(){
				
				if (this.isRequesting) {
				        console.log("请求已在处理中，5秒内不再重复发送请求。");
				        return;
				      }
				
				      // 设置标志变量为 true，表示请求已经开始
				      this.isRequesting = true;
				
				      // 执行你的确认逻辑
				      this.PayList.forEach((i, index) => {
				        if (i.checked) {
				          this.payWay = i.id;
				        }
				      });
				      console.log(this.payWay);
				      this.payParam.orderNo = this.orderNo;
				      this.payParam.payMethod = this.payWay == 3 ? 3 : 2;//支付方法：1-余额，2-微信，3-支付宝
				      this.payParam.payType = 2;//对应支付方法,余额支付-1,微信支付-2,支付宝支付-2
				      this.createPay(this.payParam);
				
				      // 设置一个定时器，在5秒后重置标志变量
				      setTimeout(() => {
				        this.isRequesting = false;
				      }, 5000);
				    
				
			},
		
			OpenpurchasePopup() {
				this.$refs.purchasePopup.open('bottom')
				
			},
			ChangePayOpt(dex) {
				this.PayList[dex].checked = true
				this.PayList.forEach((i, index) => {
					if(dex !== index) {
						this.PayList[index].checked = false
					}
					
				})
				
			},
			async getCoupon(){//查询可用优惠券
			 const param = {
			        resourceType: 3,
			        amount: this.device 
			          ? this.rechargeList[this.current - 1].androidPrice 
			          : this.rechargeList[this.current - 1].iosPrice
			      };
			      const res = await PayApi.getCoupon(param);
			      this.couponList = res;
				console.log(this.couponList);
				
				
				
				
			},
			touse(id){//使用优惠券
				 this.selectedCouponId = id;
				
				      this.$refs.couponPopup.close();
				      
				      // 选择优惠券后继续支付流程
					  this.param.id=this.current;
					   		
					  this.param.sourceType=this.device?'1':'2';
					  this.param.couponAssetsId=id;
				      this.createOrder(this.param);
				        this.OpenpurchasePopup();
			
				
				
				
				
			},
			OpencouponPopup(){
				this.$refs.couponPopup.open();
			},
			goApplePay(pid,coinCount){
				if (this.iapChannel) {
					uni.showLoading({
						title:'支付中...'
					})
					plus.payment.request(this.iapChannel, {
						'productid': pid,
						'username': '1212121121211'+pid,
					}, function(result){
						uni.hideLoading()
						store.commit('setCoin', {'operate':true,'num':coinCount});
						console.log('支付成功',result);
					}, function(e){
						uni.hideLoading()
						console.log('支付失败',e)
					});
				}
			},
			async pay() {
			      if (!this.current) {
			        uni.showToast({ title: '请选择需要充值嗒币的数量', icon: 'none', duration: 1000 });
			        return;
			      }
			      if (!this.isChecked) {
			        uni.showToast({ title: '请同意《小嗒组队嗒币充值服务协议》', icon: 'none', duration: 1000 });
			        return;
			      }
				  console.log('this.current',this.current)
				  let pid = this.rechargeList[this.current - 1].productId
				  let coinCount = this.rechargeList[this.current - 1].coinCount
				  this.goApplePay(pid,coinCount)
			      // try {
			      //   // 1. 先查询优惠券
			      //   await this.getCoupon();
			        
			      //   // 2. 根据优惠券列表决定流程
			      //   if (this.couponList.length > 0) {
			      //     this.OpencouponPopup(); // 弹出优惠券选择弹窗
			      //   } else {
			      //     // 没有优惠券直接进入支付流程
			      //    this.param.id=this.current;
			         		
			      //   this.param.sourceType=this.device?'1':'2';
			      //   this.createOrder(this.param);
			      //     this.OpenpurchasePopup();
			      //   }
			      // } catch (error) {
			      //   console.error('支付流程异常:', error);
			      // }
			    },
			async queryDaCoinMemeber() {
				
				// const res = await memberApi.DaCoinMember()
				// this.rechargeList = res.records
				// console.log(this.rechargeList);
			}
		},
		onReady() {
			this.productList = this.rechargeList.map(item=>item.productId)
			this.initIap()
		},
		onLoad() {
			// this.availableAmount=this.$store.state.user.availableAmount;
			// 判断是APP、H5还是微信小程序来控制账单样式
			// #ifdef APP-PLUS
				this.IsShow = true
			// #endif
			
			// #ifdef H5
				this.IsShow = true
			// #endif
			
			// #ifdef MP-WEIXIN
				this.IsShow = false
			// #endif
			let systemInfo = uni.getSystemInfoSync();
			if (systemInfo.platform === 'ios') {
				this.device=false;
			    console.log('当前设备是苹果设备');
			} else if (systemInfo.platform === 'android') {
				this.device=true;
			    console.log('当前设备是安卓设备');
			}
			this.queryDaCoinMemeber()
			// this.payByWxpay();
		}
	}
</script>

<style scoped lang="scss">
	.coupon-list {
	    padding: 20rpx;
	  }
	   .Cover {
	      width: 90rpx;
	      height: 100%;
	      border-right: 1px dashed #f5f5f5;
	      background-image: linear-gradient(135deg, #f7880c 0%, #fe7039 40%, #fe536f 60%, #fe4594 90%, #f73ea0 100%);
	    }
	  
	    .Coupon_item {
	      flex: 1;
	      box-shadow: 3px 3px 3px rgba(0, 0, 0, .1);
	    }
	  
	    .btn1 {
	      height: 40rpx !important;
	      line-height: 40rpx !important;
	      background-image: linear-gradient(-90deg, #f7880c 0%, #fe7039 40%, #fe536f 60%, #fe4594 90%, #f73ea0 100%);
	    }
	.PayOptions {
		width: 680rpx;
		margin: 0 auto;
		display: flex;
		align-items: center;
		margin-top: 30rpx;
		.icon {
			margin-right: 26rpx;
			image {
				width: 64rpx;
				height: 64rpx;
			}
		}
		.option {
			color: #231815;
			font-size: 28rpx;
		}
	}
.main {
	background: #fff;
	overflow: hidden;
	.content {
		width: 100%;
		background-color: #fff !important;
		.title {
			width: 750rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;
			height: 80rpx;
			padding-right: 47rpx;
			border-bottom: 1px solid rgba(204, 204, 204, .2);
			text {
				flex: 1;
				font-size: 32rpx;
				text-align: center;
				font-weight: normal;
			}
		}
	}
}
.current {
	color: #64acfa !important;
}
.borderL {
	border: 1px solid #64acfa !important;
}
.btn {
	margin: 40rpx auto 20rpx;
	text-align: center;
	font-size: 30rpx;
	height: 87rpx;
	line-height: 87rpx;
	border-radius: 50rpx;
}
.GrabOrdersBtn {
	margin-top: 20rpx;
	display: flex;
	align-items: center;
	text-align: center;
	width: 320rpx;
	height: 78rpx;
	line-height: 78rpx;
	border-radius: 50rpx;
	background: linear-gradient( 90deg, #ED65CE 0%, #E966CF 2%, #859BF0 69%, #5DB0FE 99%);
	color: #fff;
	font-size: 24rpx;
	.head_portrait {
		position: relative;
		z-index: 2;
		display: flex;
		justify-content: center;
		padding: 0 20rpx 0 45rpx;
		image {
			width: 50rpx;
			height: 50rpx;
			border-radius: 50%;
		}
		.b_img {
			position: absolute;
			top: -26rpx;
			left: 20rpx;
		}
	}
	.txt {
		flex: 1;
	}
	.arr_icon {
		display: flex;
		align-items: center;
		margin: 0 15rpx 0 20rpx;
		image {
			width: 10rpx;
			height: 10rpx;
			transform: rotate(180deg);
		}
	}
}
.pt-300 {
	padding-top: 300rpx;
}
.mt-200 {
	margin-top: 200rpx;
}
</style>
